from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Student(models.Model):
    GENDER_CHOICES = (
        ('M', '男'),
        ('F', '女'),
    )
    
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name='用户账号')
    student_id = models.CharField('学号', max_length=20, unique=True)
    name = models.CharField('姓名', max_length=50)
    gender = models.CharField('性别', max_length=1, choices=GENDER_CHOICES)
    age = models.IntegerField('年龄')
    grade = models.CharField('年级', max_length=20)
    major = models.CharField('专业', max_length=50)
    phone = models.CharField('电话', max_length=15)
    email = models.EmailField('邮箱')
    admission_date = models.DateField('入学日期')
    
    class Meta:
        verbose_name = '学生'
        verbose_name_plural = '学生'
    
    def __str__(self):
        return f"{self.name} - {self.student_id}" 

@receiver(post_save, sender=Student)
def create_user_for_student(sender, instance, created, **kwargs):
    if created and not instance.user:
        # 创建用户账号
        username = instance.student_id
        user = User.objects.create_user(
            username=username,
            password=username,  # 初始密码设置为学号
            email=instance.email,
            first_name=instance.name
        )
        # 关联学生和用户
        instance.user = user
        instance.save()

class Teacher(models.Model):
    GENDER_CHOICES = (
        ('M', '男'),
        ('F', '女'),
    )
    
    TITLE_CHOICES = (
        ('助教', '助教'),
        ('讲师', '讲师'),
        ('副教授', '副教授'),
        ('教授', '教授'),
    )
    
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name='用户账号')
    teacher_id = models.CharField('工号', max_length=20, unique=True)
    name = models.CharField('姓名', max_length=50)
    gender = models.CharField('性别', max_length=1, choices=GENDER_CHOICES)
    age = models.IntegerField('年龄')
    title = models.CharField('职称', max_length=10, choices=TITLE_CHOICES)
    department = models.CharField('所属院系', max_length=50)
    phone = models.CharField('电话', max_length=15)
    email = models.EmailField('邮箱')
    hire_date = models.DateField('入职日期')
    
    class Meta:
        verbose_name = '教师'
        verbose_name_plural = '教师'
    
    def __str__(self):
        return f"{self.name} - {self.title}" 

class Course(models.Model):
    name = models.CharField('课程名称', max_length=100)
    code = models.CharField('课程代码', max_length=20, unique=True)
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, verbose_name='授课教师')
    description = models.TextField('课程描述', blank=True)
    
    class Meta:
        verbose_name = '课程'
        verbose_name_plural = '课程'
    
    def __str__(self):
        return f"{self.name} - {self.teacher.name}"

class StudentScore(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, verbose_name='学生')
    course = models.ForeignKey(Course, on_delete=models.CASCADE, verbose_name='课程')
    score = models.DecimalField('成绩', max_digits=5, decimal_places=2,
                              validators=[MinValueValidator(0), MaxValueValidator(100)])
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    class Meta:
        verbose_name = '学生成绩'
        verbose_name_plural = '学生成绩'
        unique_together = ['student', 'course']  # 每个学生在每门课只能有一个成绩
    
    def __str__(self):
        return f"{self.student.name} - {self.course.name} - {self.score}"

class TeacherRating(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, verbose_name='学生')
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, verbose_name='教师')
    course = models.ForeignKey(Course, on_delete=models.CASCADE, verbose_name='课程')
    rating = models.IntegerField('评分', 
                               validators=[MinValueValidator(1), MaxValueValidator(5)])
    comment = models.TextField('评价', blank=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    
    class Meta:
        verbose_name = '教师评分'
        verbose_name_plural = '教师评分'
        unique_together = ['student', 'teacher', 'course']  # 每个学生对每个教师的每门课只能评价一次
    
    def __str__(self):
        return f"{self.student.name} 评价 {self.teacher.name} - {self.rating}分"